// import axios from 'axios'

import { INNER_COMPS } from "@/config/config"
import { saveAs } from 'file-saver';
function isObject(obj) {
  return typeof (obj) === 'object' && (!Array.isArray(obj))
}
export function isArray(obj) {
  return Array.isArray(obj)
}

export function isFunction(obj) {
  return (obj && obj instanceof Function)
}

export function isString(obj) {
  return typeof (obj) === 'string'
}
function combineValue(v1, v2) {
  if (isString(v1)) {
    return v2
  }
  if (isArray(v1)) {
    if (isArray(v2)) {
      let v = Array.from(v1)
      v = v.concat(v2)
      return v
    }
    else {
      return v2
    }
  }
  if (isObject(v1)) {
    if (isObject(v2)) {
      const v = {}
      for (let k in v1) {
        if (k in v2) {
          v[k] = combineValue(v1[k], v2[k])
        }
        else {
          v[k] = v1[k]
        }
      }
      for (let k in v2) {
        if (k in v1) {
          continue
        }
        v[k] = v2[k]
      }
      return v
    }
    else {
      return v2
    }
  }
}

function getConfigData(key, cfg) {
  let k = key.split('.')[1]

  if (cfg[k]) {
    return cfg[k]
  }

  if (k in window.FORM_CONFIG) {
    // console.log(window.FORM_CONFIG[k])
    return window.FORM_CONFIG[k]
  }
}

export function parseGridForm(form = [], obj = {}) {
  form.forEach(item => {
    if (item.level === 'item') {
      if (item.field in obj) {
        obj[item.field] = combineValue(obj[item.field], item.value)
      }
      else {
        obj[item.field] = item.value
      }
    }
    else {
      if (isArray(item.layout) && item.layout.length > 0) {
        parseGridForm(item.layout, obj)
      }

    }
  })
  return obj
}
// INNER_COMPS

function innerCompnentReplace(obj) {
  let key = obj['field'].slice(1, obj['field'].length)
  let keys = key.split('==')
  let inner_type = keys[0]
  let field = keys[1]
  // console.log(inner_type)
  if (inner_type in INNER_COMPS) {
    let nobj = Object.assign({}, INNER_COMPS[inner_type])
    nobj.field = field
    nobj.value = obj.value
    nobj.wrap = obj.wrap
    nobj.props = obj.props
    nobj.info = obj.info
    nobj.title = obj.title
    nobj.hidden = obj.hidden || false
    nobj.display = obj.display || true
    return nobj
  }
}

export function parseConfig(obj, config = {}, vm = {}, t2f = undefined) {
  // console.log(obj)
  if (obj === undefined || obj === null) {
    return obj
  }
  if (isObject(obj)) {
    if ('field' in obj) {
      if (obj['field'].startsWith('$')) {
        obj = innerCompnentReplace(obj)
      }
      if (t2f && obj && 'field' in obj) {
        obj['field'] = obj['title'] || obj['field']
      }

     
    }
    if ('type' in obj) {
      if (obj['type'] === 'upload') {
        obj['props']['onSuccess'] = function (e, t) { t.url = e.data }
        obj['props']['action'] = '${config.upload_url}'
        obj['props']['headers'] = {
          "Authorization": "${config.token}"
        }
        obj['props']['onExceed'] = function (f, fs) { }
      }
      else if (obj['type'] === 'FcRow') {
        let t = obj['children'][0]['children']
        if (t && t.length > 0) {
          if (t[0]['type'] === 'el-divider') {
            if (t[0]['children'][0].startsWith('$group')) {
              let ps = t[0]['children'][0].split('==')[1]
              let tobj = {
                type: 'group',
                field: ps,
                title: ps,
                props: {
                  rules: t.slice(1)
                }
              }
              obj = tobj
            }
            else if (t[0]['children'][0].startsWith('$object')) {

            }
          }
        }
      }

      if (obj['type'] === 'input') {
        obj['type'] = 'listen-input'
      }
    }

    if (obj && 'value' in obj && 'label' in obj) {
      obj.value = obj.label
    }

    for (let k in obj) {
      if (isObject(obj[k])) {
        obj[k] = parseConfig(obj[k], config, vm, t2f);
      }
      else if (isArray(obj[k])) {
        obj[k] = obj[k].map(v => parseConfig(v, config, vm, t2f));
      }
      else if (isString(obj[k])) {
        // console.log(obj[k])
        if (obj[k].startsWith('@') || obj[k].startsWith('$')) {
          if (!!obj[k].match(/\$\{.*\}/)) {
            let key = obj[k].slice(2, -1)
            obj[k] = getConfigData(key, config);
          }
          else if (!!obj[k].match(/\@\{.*\}/)) {
            obj[k] = (new Function('vm', 'return ' + obj[k].slice(2, -1)))(vm)
            // console.log(obj[k])
          }

        }


      }
    }
    // return obj;
  }
  else if (isArray(obj)) {
    obj = obj.map(v => parseConfig(v, config, vm, t2f));
  }
  else if (isString(obj)) {
    if (!!obj.match(/\$\{.*\}/)) {
      let key = obj.slice(2, -1)
      obj = getConfigData(key, config);
      // console.log(obj)
    }
    else if (!!obj.match(/\@\{.*\}/)) {
      obj = (new Function('vm', 'return ' + obj.slice(2, -1)))(vm)
    }

  }
  // console.log(obj)
  return obj;
}

export function mergeList(a1 = [], a2 = [], key = '_id') {
  let a = []
  let u = []
  a1.forEach(uu => {
    a.push(uu)
    u.push(uu[key])
  })
  a2.forEach(uu => {
    if (!u.includes(uu[key])) {
      a.push(uu)
    }
  })
  return a
}

export function uuid() {
  var temp_url = URL.createObjectURL(new Blob());
  var uuid = temp_url.toString(); // blob:https://xxx.com/b250d159-e1b6-4a87-9002-885d90033be3
  URL.revokeObjectURL(temp_url);
  return uuid.substr(uuid.lastIndexOf("/") + 1);
}

export function generateID() {
  let date = new Date()
  let year = date.getFullYear()
  let mounth = date.getMonth() + 1
  let day = date.getDate()

  let hour = date.getHours()
  let mins = date.getMinutes()
  let sec = date.getSeconds()

  return '' + year +
    (mounth < 10 ? '0' : '') + mounth +
    (day < 10 ? '0' : '') + day +
    (hour < 10 ? '0' : '') + hour +
    (mins < 10 ? '0' : '') + mins +
    (sec < 10 ? '0' : '') + sec +
    (Math.round(Math.random() * 100))
}

export function getIpAddress() {
  // let data = await axios.get('http://pv.sohu.com/cityjson?ie=utf-8')
  // console.log(data)
  return returnCitySN
}

export function getBrowserInfo() {
  var agent = navigator.userAgent.toLowerCase();
  // console.log(agent);
  var arr = [];
  var system = agent.split(' ')[1].split(' ')[0].split('(')[1];
  arr.push(system);
  var regStr_edge = /edge\/[\d.]+/gi;
  var regStr_ie = /trident\/[\d.]+/gi;
  var regStr_ff = /firefox\/[\d.]+/gi;
  var regStr_chrome = /chrome\/[\d.]+/gi;
  var regStr_saf = /safari\/[\d.]+/gi;
  var regStr_opera = /opr\/[\d.]+/gi;
  //IE
  if (agent.indexOf("trident") > 0) {
    arr.push(agent.match(regStr_ie)[0].split('/')[0]);
    arr.push(agent.match(regStr_ie)[0].split('/')[1]);
    return arr;
  }
  //Edge
  if (agent.indexOf('edge') > 0) {
    arr.push(agent.match(regStr_edge)[0].split('/')[0]);
    arr.push(agent.match(regStr_edge)[0].split('/')[1]);
    return arr;
  }
  //firefox
  if (agent.indexOf("firefox") > 0) {
    arr.push(agent.match(regStr_ff)[0].split('/')[0]);
    arr.push(agent.match(regStr_ff)[0].split('/')[1]);
    return arr;
  }
  //Opera
  if (agent.indexOf("opr") > 0) {
    arr.push(agent.match(regStr_opera)[0].split('/')[0]);
    arr.push(agent.match(regStr_opera)[0].split('/')[1]);
    return arr;
  }
  //Safari
  if (agent.indexOf("safari") > 0 && agent.indexOf("chrome") < 0) {
    arr.push(agent.match(regStr_saf)[0].split('/')[0]);
    arr.push(agent.match(regStr_saf)[0].split('/')[1]);
    return arr;
  }
  //Chrome
  if (agent.indexOf("chrome") > 0) {
    arr.push(agent.match(regStr_chrome)[0].split('/')[0]);
    arr.push(agent.match(regStr_chrome)[0].split('/')[1]);
    return arr;
  } else {
    arr.push('请更换主流浏览器,例如chrome,firefox,opera,safari,IE,Edge!')
    return arr;
  }
}
export function writeJSON(data, name) {
  let s = JSON.stringify(data)
  let eleLink = document.createElement('a');
  eleLink.download = name + ".json";
  eleLink.style.display = 'none';
  // 字符内容转变成blob地址
  let blob = new Blob([s]);
  eleLink.href = URL.createObjectURL(blob);
  // 触发点击
  document.body.appendChild(eleLink);
  eleLink.click();
  // 然后移除
  document.body.removeChild(eleLink);
}

export function loadJSON() {
  return new Promise((resolve, reject) => {
    let e = document.createElement("input");
    e.type = "file";
    e.style.display = "none";
    let that = this;
    e.addEventListener("change", (ev) => {
      var selectedFile = e.files[0]; //获取读取的File对象
      var name = selectedFile.name; //读取选中文件的文件名
      var size = selectedFile.size; //读取选中文件的大小
      console.log("文件名:" + name + "大小：" + size);
      var reader = new FileReader(); //这里是核心！！！读取操作就是由它完成的。
      reader.readAsText(selectedFile); //读取文件的内容

      reader.onload = function () {
        resolve(this.result)
      };
      reader.onerror = function () {
        reject(this.error)
      }
    });
    e.click();
  })

}

export function downLoadByUrl(url, token, fname) {
  var xhr = new XMLHttpRequest();
  //GET请求,请求路径url,async(是否异步)
  xhr.open('GET', url, true);
  //设置请求头参数的方式,如果没有可忽略此行代码
  xhr.setRequestHeader("Authorization", token);
  //设置响应类型为 blob
  xhr.responseType = 'blob';
  //关键部分
  xhr.onload = function (e) {
    //如果请求执行成功
    console.log(e)
    if (this.status == 200) {
      var blob = this.response;
      saveAs(blob, fname)
    }
  
  };
  xhr.send();
}

